package com.fengyunhe.common.utils;


import com.fengyunhe.common.AppContext;
import org.apache.commons.io.FileUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

/**
 * @author yangyan
 * Created by Administrator on 2014/8/18.
 */
public class MultipartFileUtils
{
    /**
     * 文件存放前缀路径
     * @return
     */
    public static String getFilePathPrefix()
    {
        return File.separator + "upload" + File.separator + "activity" + File.separator + new SimpleDateFormat("yyyyMMdd").format(new Date()) + File.separator;
    }

    /**
     * 重置图片名
     * @return
     */
    public static String getSaveFilename(MultipartFile upFile)
    {
        if(isExists(upFile))
        {
            String [] uuid = UUID.randomUUID().toString().split("-");
            String filename = upFile.getOriginalFilename();
            filename = uuid[0] + uuid[1] + uuid[2] + uuid[3] + uuid[4] + filename.substring(filename.indexOf("."));
             return filename;
        }
        return upFile.getOriginalFilename();
    }

    /**
     * 检查文件是否存在
     * @param action
     * @return
     */
    public static boolean isExists(MultipartFile action)
    {
        if(null != action && action.getSize() > 0)
        {
            return true;
        }
        return false;
    }

    /**
     * 保存文件
     * @param upfile
     * @param savePath
     * @throws java.io.IOException
     */
    public static String saveFile(MultipartFile upfile, String savePath) throws IOException
    {
        FileUtils.copyInputStreamToFile(upfile.getInputStream(), new File(AppContext.getAppRealPath() + savePath));
        return savePath;
    }

    /**
     * 保存文件
     * @param upfile
     * @throws java.io.IOException
     */
    public static String saveFile(MultipartFile upfile) throws IOException
    {
        String savePath = getFilePathPrefix() + getSaveFilename(upfile);
        FileUtils.copyInputStreamToFile(upfile.getInputStream(), new File(AppContext.getAppRealPath() + savePath));
        return savePath;
    }

    /**
     * 广告主-证书存放路径
     * @return
     */
    public static String getFilePathPrefixForAdvertiser(String licenseType)
    {
        return File.separator + "upload" + File.separator + "advertiser" + File.separator+licenseType+File.separator + new SimpleDateFormat("yyyyMMdd").format(new Date()) + File.separator;
    }

    /**
     * 上传广告主证件用
     * @param upfile
     * @return
     * @throws IOException
     */
    public static String saveFileForAdvertiserLicense(MultipartFile upfile,String licenseType) throws IOException
    {
        String savePath = getFilePathPrefixForAdvertiser(licenseType) + getSaveFilename(upfile);
        FileUtils.copyInputStreamToFile(upfile.getInputStream(), new File(AppContext.getAppRealPath() + savePath));
        return savePath;
    }

}
